#include "thread_pool.h"

static int log_fd = -1;
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;

int logger_init(const char *log_file_name){
    log_fd = open(log_file_name, O_WRONLY | O_CREAT | O_APPEND, 0664);
    ERROR_CHECK(log_fd, -1, "open failed in logger_init()");
    return 0;
}
int logger_close(){
    if(log_fd != -1){
        close(log_fd);
        log_fd = -1;
        return 0;
    }
    return -1;
}
void log_info(const char *type, const char *content, const char *file, int line, const char *function){
    printf("Add Log in %s:%d:%s\n", file, line, function);
    char info[4096] = {0};
    char time_now[128] = {0};
    time_t time_data_now = time(NULL);
    ctime_r(&time_data_now, time_now);
    // 去掉末尾换行符
    time_now[strlen(time_now) - 1] = '\0';
    int len = snprintf(info, sizeof(info),
        "[%s][LOG_INFO][%s:%d@%s] Type=%s | Content=%s\n",
        time_now, file, line, function, type, content);
    pthread_mutex_lock(&log_mutex);
    if(log_fd != -1){
        write(log_fd, info, len);
    }
    pthread_mutex_unlock(&log_mutex);
}
